<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Java并发编程2(锁-Sychronized) | XuanCode</title><meta name="author" content="xuanskeys"><meta name="copyright" content="xuanskeys"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="认识Java对象头  32位虚拟机对象头：   64位虚拟机对象头：     1.Mark Word（标记字）:  Mark Word是对象头的一部分，用于存储对象自身的哈希码、GC分代年龄、锁状态标志、线程持有的锁、偏向线程ID（或偏向时间戳）、偏向模式以及锁的状态等信息。 标记字的大小和具体内容可能因JVM实现的不同而有所变化。例如，在64位JVM上，默认情况下Mark Word占用64位（8">
<meta property="og:type" content="article">
<meta property="og:title" content="Java并发编程2(锁-Sychronized)">
<meta property="og:url" content="http://xuanskeys.github.io/2025/04/20/JUC2/index.html">
<meta property="og:site_name" content="XuanCode">
<meta property="og:description" content="认识Java对象头  32位虚拟机对象头：   64位虚拟机对象头：     1.Mark Word（标记字）:  Mark Word是对象头的一部分，用于存储对象自身的哈希码、GC分代年龄、锁状态标志、线程持有的锁、偏向线程ID（或偏向时间戳）、偏向模式以及锁的状态等信息。 标记字的大小和具体内容可能因JVM实现的不同而有所变化。例如，在64位JVM上，默认情况下Mark Word占用64位（8">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://xuanskeys.github.io/image/person.jpg">
<meta property="article:published_time" content="2025-04-20T01:56:29.000Z">
<meta property="article:modified_time" content="2025-04-20T01:59:05.017Z">
<meta property="article:author" content="xuanskeys">
<meta property="article:tag" content="1">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://xuanskeys.github.io/image/person.jpg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "Java并发编程2(锁-Sychronized)",
  "url": "http://xuanskeys.github.io/2025/04/20/JUC2/",
  "image": "http://xuanskeys.github.io/image/person.jpg",
  "datePublished": "2025-04-20T01:56:29.000Z",
  "dateModified": "2025-04-20T01:59:05.017Z",
  "author": [
    {
      "@type": "Person",
      "name": "xuanskeys",
      "url": "http://xuanskeys.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/image/%E5%AF%BF%E5%8F%B8.png"><link rel="canonical" href="http://xuanskeys.github.io/2025/04/20/JUC2/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"未找到符合您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Java并发编程2(锁-Sychronized)',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/styles/main.css"><script src="/styles/fish.js"></script><script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script><meta name="generator" content="Hexo 7.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load', preloader.endLoading)

  if (false) {
    btf.addGlobalFn('pjaxSend', preloader.initLoading, 'preloader_init')
    btf.addGlobalFn('pjaxComplete', preloader.endLoading, 'preloader_end')
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/image/person.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">10</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><span class="site-page group"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></span><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url(/image/background.jpg);"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">XuanCode</span></a><a class="nav-page-title" href="/"><span class="site-name">Java并发编程2(锁-Sychronized)</span></a></span><div id="menus"><div id="search-button"><span class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></span></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><span class="site-page group"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></span><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">Java并发编程2(锁-Sychronized)</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2025-04-20T01:56:29.000Z" title="发表于 2025-04-20 09:56:29">2025-04-20</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-04-20T01:59:05.017Z" title="更新于 2025-04-20 09:59:05">2025-04-20</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/">Java并发编程</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1><span id="认识java对象头">认识Java对象头</span></h1><p><img src="/./../images/62007980c9464950aa873bb9b92923c2.png" alt="img"><img src="" alt="点击并拖拽以移动"> </p>
<p>32位虚拟机对象头：</p>
<p><img src="/./../images/015d875a32564d24bc821129428b6259.png" alt="img"><img src="" alt="点击并拖拽以移动"> </p>
<p>64位虚拟机对象头： </p>
<p><img src="/./../images/caa69615a9754ef68b053d75b2ab6cc4.png" alt="img"><img src="" alt="点击并拖拽以移动"> </p>
<blockquote>
<p><strong>1.Mark Word（标记字）:</strong></p>
<ul>
<li>Mark Word是对象头的一部分，用于存储对象自身的哈希码、GC分代年龄、锁状态标志、线程持有的锁、偏向线程ID（或偏向时间戳）、偏向模式以及锁的状态等信息。</li>
<li>标记字的大小和具体内容可能因JVM实现的不同而有所变化。例如，在64位JVM上，默认情况下Mark Word占用64位（8字节），而在32位JVM上则是32位（4字节）。</li>
</ul>
<p><strong>2.Class Pointer（类指针）:</strong></p>
<ul>
<li>这是指向该对象对应类（Class）的指针，通过这个指针可以访问到对象所属类的元数据（如方法表、字段描述等）。类指针的大小依赖于JVM的具体实现及其是否开启了压缩指针（Compressed Oop）选项。</li>
<li>在某些情况下，比如当使用了-XX:+UseCompressedClassPointers选项时，类指针会被压缩以节省内存。</li>
</ul>
<p><strong>3.Array Length（数组长度，仅适用于数组对象）:</strong></p>
<ul>
<li>如果对象是一个数组，则对象头还需要额外的空间来存储数组的长度。这是因为非数组对象不需要知道其“长度”，但数组需要这个信息以便进行边界检查等操作。</li>
</ul>
</blockquote>
<hr>
<h1><span id="sychronized锁原理">sychronized锁原理</span></h1><p><img src="/./../images/d51144c25ee94925aefe66676e1fb4ea.png" alt="img"><img src="" alt="点击并拖拽以移动"> </p>
<h2><span id="基本概念">基本概念</span></h2><ul>
<li><strong>对象头（Object Header）：</strong>每个Java对象都有一个对象头，其中包含了一些元数据信息。对于普通对象来说，这部分包括Mark Word和Class Pointer。Mark Word存储了对象的哈希码、GC分代年龄、锁状态标志等信息。</li>
<li><strong>Monitor（监视器&#x2F;管程）：</strong>这是JVM内部的一种同步机制。每个对象都关联有一个监视器锁。当一个线程获取到这个锁时，它可以进入临界区；其他试图进入同一临界区的线程必须等待，直到第一个线程释放锁。</li>
</ul>
<h2><span id="工作原理">工作原理</span></h2><h3><span id="1作用在方法上">1.作用在方法上</span></h3><ul>
<li>使用synchronized修饰一个实例方法时，该方法被调用时会自动获取当前实例（即this）的monitor锁。</li>
<li>如果是静态方法，则锁定的是该类的Class对象。</li>
</ul>
<h3><span id="2作用在代码块上">2.作用在代码块上</span></h3><ul>
<li>使用synchronized代码块可以更灵活地指定要锁定的对象，获取的是括号中的对象。</li>
</ul>
<h2><span id="工作机制">工作机制</span></h2><blockquote>
<p>字节码层面：使用synchronized关键字时，编译器会将同步块或方法转换为特定的字节码指令。对于同步方法，编译器会在方法信息中设置一个标志位（ACC_SYNCHRONIZED）。对于同步代码块，则会生成monitorenter和monitorexit指令。</p>
</blockquote>
<p><strong>monitorenter 和 monitorexit 指令：</strong></p>
<ul>
<li>monitorenter：每个对象都有一个与之关联的monitor（监视器锁）。当线程执行到monitorenter指令时，它尝试获取该对象的monitor。如果monitor未被其他线程持有，则当前线程成功获取monitor并继续执行；否则，线程将被阻塞直到获得monitor。</li>
<li>monitorexit：当线程执行完同步代码块后，会执行monitorexit指令以释放monitor，允许其他等待获取该monitor的线程继续执行。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test2</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">Object</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Object</span>();</span><br><span class="line">    <span class="keyword">static</span> <span class="type">int</span> <span class="variable">cnt</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">       <span class="keyword">synchronized</span> (lock) &#123;</span><br><span class="line">           cnt ++;</span><br><span class="line">       &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<p>上段代码main方法生成的字节码指令如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(java.lang.String[])</span>;</span><br><span class="line">  Code:</span><br><span class="line">     <span class="number">0</span>: getstatic     #<span class="number">2</span>                  <span class="comment">// Field lock:Ljava/lang/Object;</span></span><br><span class="line">     <span class="number">3</span>: dup</span><br><span class="line">     <span class="number">4</span>: astore_1</span><br><span class="line">     <span class="number">5</span>: monitorenter                     <span class="comment">// 获取锁</span></span><br><span class="line">     <span class="number">6</span>: getstatic     #<span class="number">3</span>                  <span class="comment">// Field cnt:I</span></span><br><span class="line">     <span class="number">9</span>: iconst_1</span><br><span class="line">    <span class="number">10</span>: iadd</span><br><span class="line">    <span class="number">11</span>: putstatic     #<span class="number">3</span>                  <span class="comment">// Field cnt:I</span></span><br><span class="line">    <span class="number">14</span>: aload_1</span><br><span class="line">    <span class="number">15</span>: monitorexit                      <span class="comment">// 释放锁</span></span><br><span class="line">    <span class="number">16</span>: <span class="keyword">goto</span>          <span class="number">24</span></span><br><span class="line">    <span class="number">19</span>: astore_2</span><br><span class="line">    <span class="number">20</span>: aload_1</span><br><span class="line">    <span class="number">21</span>: monitorexit                      <span class="comment">// 确保在异常情况下也释放锁</span></span><br><span class="line">    <span class="number">22</span>: aload_2</span><br><span class="line">    <span class="number">23</span>: athrow</span><br><span class="line">    <span class="number">24</span>: <span class="keyword">return</span></span><br><span class="line">  Exception table:</span><br><span class="line">     from    to  target type</span><br><span class="line">         <span class="number">6</span>    <span class="number">16</span>    <span class="number">19</span>   any</span><br><span class="line">        <span class="number">19</span>    <span class="number">22</span>    <span class="number">19</span>   any</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<h2><span id="jvm优化锁">JVM优化锁</span></h2><blockquote>
<p><strong>1.无锁状态：</strong></p>
<ul>
<li>这是对象的初始状态，没有任何线程持有该对象的Monitor锁。</li>
</ul>
<p><strong>2.偏向锁（Biased Locking）：</strong></p>
<ul>
<li>偏向锁是针对单线程访问场景的一种优化。它假设如果一个线程获得了某个对象的锁，那么接下来很可能还是这个线程继续访问该对象。</li>
<li>当一个线程第一次进入同步块时，会尝试获取偏向锁，并将线程ID记录在对象头中。如果之后还是同一个线程进入同步块，则不需要再次获取锁，减少了锁获取的开销。</li>
<li>如果有其他线程试图获取偏向锁，则需要撤销偏向锁并升级为轻量级锁。</li>
</ul>
<p><strong>3.轻量级锁（Lightweight Locking）：</strong></p>
<ul>
<li>当存在少量锁竞争时，使用轻量级锁来代替重量级锁，以提高性能。</li>
<li>轻量级锁通过CAS（Compare And Swap）操作尝试原子性地获得锁。如果成功，则线程可以进入临界区；如果失败，表示存在锁竞争，锁可能会升级为重量级锁。</li>
</ul>
<p><strong>4.重量级锁（Heavyweight Locking）：</strong></p>
<ul>
<li>当锁竞争加剧时，JVM会将锁升级为重量级锁。重量级锁涉及到操作系统层面的线程挂起和恢复操作，因此开销较大。</li>
<li>在这种状态下，所有竞争锁的线程都会被阻塞，直到当前持有锁的线程释放锁为止。</li>
</ul>
<p><strong>5.自旋锁（Spin Lock）：</strong></p>
<ul>
<li>自旋锁不是一种独立的锁类型，而是一种策略。当一个线程尝试获取锁时，它可以选择“自旋”一段时间，而不是立即进入阻塞状态。这样可以在等待锁释放的过程中减少上下文切换的开销。</li>
<li>Java中的自旋锁通常与轻量级锁结合使用，在某些情况下可以作为一种优化手段。</li>
</ul>
<p><strong>6.可重入锁（Reentrant Lock）：</strong></p>
<ul>
<li>synchronized机制本身就是可重入的，这意味着如果一个线程已经持有了某个对象的锁，它可以再次获取相同的锁而不会导致死锁。</li>
<li>每次重新获取锁时，计数器会增加；每次释放锁时，计数器会减少，直到计数器归零才真正释放锁。</li>
</ul>
</blockquote>
<p>在Java中默认第一次给对象加锁就是<strong>偏向锁</strong>（默认延迟加载），假如t1线程已经给obj加上锁（偏向锁）了，当有另外一个线程t2也试图获取同一把锁时，偏向锁升级为轻量级锁。</p>
<p><strong>轻量级锁</strong>通过使用CAS操作尝试将对象头中的Mark Word更新为指向当前线程的Lock Record的指针。如果成功，则线程获得了轻量级锁，并继续执行；如果失败（意味着存在锁竞争），则会尝试进行锁膨胀，轻量级锁尝试升级为重量级锁。</p>
<p><strong>重量级锁</strong>的核心是Monitor（监视器锁），如果Monitor已被其他线程持有，则试图获取锁的线程将被放入Entry Set中等待。此时，线程会进入阻塞状态，即线程会被挂起，不会占用CPU资源，直到Monitor锁被释放并且该线程有机会重新尝试获取锁，这允许Entry Set中的一个或多个线程重新竞争Monitor锁。如果有线程处于Wait Set中，那么根据调用的是notify()还是notifyAll()方法，相应的线程会被移动到Entry Set中，重新参与Monitor锁的竞争。</p>
<h2><span id="monitor锁">Monitor锁</span></h2><ul>
<li><strong>Owner（所有者）：</strong>指向当前持有Monitor的线程。</li>
<li><strong>Entry Set（入口集）：</strong>等待获取Monitor锁的线程队列。如果一个线程尝试进入一个已经被其他线程持有的同步块或方法，则该线程会被放入这个队列中，直到Monitor被释放并且该线程有机会重新尝试获取锁。</li>
<li><strong>Wait Set（等待集）：</strong>调用了wait()方法并正在等待某个条件满足的线程集合。这些线程暂时释放了Monitor，并且不会参与锁的竞争，直到另一个线程调用notify()或notifyAll()方法通知它们可以继续执行。</li>
</ul>
<hr>
<h2><span id="waitx2fnotify">wait&#x2F;notify</span></h2><blockquote>
<ul>
<li><strong>wait()：</strong>使当前线程等待，直到另一个线程调用同一个对象上的notify()或notifyAll()方法。调用wait()时，当前线程会释放它持有的对象锁，并进入该对象的“等待集”。只有当其他线程调用了相应的通知方法并且当前线程被选中（对于notify()）或所有等待的线程都被唤醒（对于notifyAll()），当前线程才能重新获取锁并继续执行。</li>
<li><strong>notify()：</strong>随机唤醒一个正在等待该对象监视器的单个线程。如果多个线程都在等待，则选择其中一个线程进行唤醒。被唤醒的线程并不能立即执行，而是要等到当前线程退出同步代码块并释放锁之后。</li>
<li><strong>notifyAll()：</strong>唤醒所有正在等待该对象监视器的线程。尽管所有线程都会被唤醒，但只有一个线程能够成功获得锁并继续执行；其余线程将再次进入等待状态或者竞争锁。</li>
</ul>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> <span class="keyword">static</span> <span class="type">Object</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Object</span>();</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line"></span><br><span class="line">    <span class="type">Thread</span> <span class="variable">t1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (lock) &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;running &#123;&#125;&quot;</span>, System.currentTimeMillis());</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                lock.wait();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            log.debug(<span class="string">&quot;end... &#123;&#125;&quot;</span>, System.currentTimeMillis());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,<span class="string">&quot;t1&quot;</span>);</span><br><span class="line">    <span class="type">Thread</span> <span class="variable">t2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (lock) &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;running &#123;&#125;&quot;</span>, System.currentTimeMillis());</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                lock.wait();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            log.debug(<span class="string">&quot;end... &#123;&#125;&quot;</span>, System.currentTimeMillis());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, <span class="string">&quot;t2&quot;</span>);</span><br><span class="line">    t1.start();</span><br><span class="line">    t2.start();</span><br><span class="line">    Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">    <span class="keyword">synchronized</span> (lock) &#123;</span><br><span class="line">        log.debug(<span class="string">&quot;唤醒线程&quot;</span>);</span><br><span class="line">        <span class="comment">// lock.notify(); // 唤醒一个线程</span></span><br><span class="line">        lock.notifyAll(); <span class="comment">// 唤醒所有线程</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<p><img src="/./../images/d6aa6da84d834c43a424844811bd47fe.png" alt="img"><img src="" alt="点击并拖拽以移动">  调用wait就是当前线程得到了对象锁了，但是我不往下执行了，我把锁释放给其他线程先去执行，我自己到<strong>Wait Set（等待集）</strong>中去，有人（线程）叫我（notify）我再去排队进入<strong>Entry Set（入口集）</strong>，每有人叫我我就继续等着。（感觉很像坐高铁，我虽然进了高铁站，但是车次没有轮到我，那么我就继续等着，如果叫到我了我就去排队等待坐车）</p>
<h2><span id="parkx2funpark">park&#x2F;unpark</span></h2><p>它们是 LockSupport 类中的方法</p>
<blockquote>
<p>&#x2F;&#x2F; 暂停当前线程</p>
<p>LockSupport.park();</p>
<p>&#x2F;&#x2F; 恢复某个线程的运行</p>
<p>LockSupport.unpark(暂停线程对象)</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j(topic = &quot;c.thread&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test4</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;t1 running &#123;&#125;&quot;</span>, System.currentTimeMillis());</span><br><span class="line">            LockSupport.park();</span><br><span class="line">            log.debug(<span class="string">&quot;t1 end &#123;&#125;&quot;</span>, System.currentTimeMillis());</span><br><span class="line">        &#125;, <span class="string">&quot;t1&quot;</span>);</span><br><span class="line">        t1.start();</span><br><span class="line">        sleep(<span class="number">1000</span>);</span><br><span class="line">        LockSupport.unpark(t1);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<p> 执行结果：</p>
<p>16:10:58 [t1] c.thread - t1 running 1742631058230<br> 16:10:59 [t1] c.thread - t1 end 1742631059240</p>
<h1><span id="线程状态转换案例">线程状态转换案例</span></h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j(topic = &quot;c.thread&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test5</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">Object</span> <span class="variable">obj</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Object</span>();</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (obj) &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;running t1&quot;</span>);</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    sleep(<span class="number">1000</span>);</span><br><span class="line">                    obj.notify();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (obj) &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;running t2&quot;</span>);</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    obj.wait();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t2&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t3</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (obj) &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;running t3&quot;</span>);</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    obj.wait();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t2&quot;</span>);</span><br><span class="line">        t1.start();</span><br><span class="line">        t2.start();</span><br><span class="line">        t3.start();</span><br><span class="line">        log.debug(<span class="string">&quot;t1 &#123;&#125; t2 &#123;&#125; t3 &#123;&#125;&quot;</span>, t1.getState(), t2.getState(), t3.getState());</span><br><span class="line">        sleep(<span class="number">100</span>);</span><br><span class="line">        log.debug(<span class="string">&quot;t1 &#123;&#125; t2 &#123;&#125; t3 &#123;&#125;&quot;</span>, t1.getState(), t2.getState(), t3.getState());</span><br><span class="line">        sleep(<span class="number">2000</span>);</span><br><span class="line">        log.debug(<span class="string">&quot;t1 &#123;&#125; t2 &#123;&#125; t3 &#123;&#125;&quot;</span>, t1.getState(), t2.getState(), t3.getState());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<p>运行结果：</p>
<p>21:08:27 [main] c.thread - t1 RUNNABLE t2 RUNNABLE t3 RUNNABLE<br> 21:08:27 [t2] c.thread - running t2<br> 21:08:27 [t2] c.thread - running t3<br> 21:08:27 [Thread-0] c.thread - running t1<br> 21:08:27 [main] c.thread - t1 TIMED_WAITING t2 WAITING t3 WAITING<br> 21:08:29 [main] c.thread - t1 TERMINATED t2 TERMINATED t3 WAITING </p>
<p>第一次打印分析：三个线程都启动了</p>
<p>第二次打印分析：此时t1在sleep，t2和t3都在wait</p>
<p>第三次打印分析：t1sleep完了，然后随机唤醒一个waiting的线程，所以t1和t2都执行完了，t3没有人唤醒它</p>
<h1><span id="死锁">死锁</span></h1><h2><span id="概念">概念</span></h2><blockquote>
<p>死锁（Deadlock）是指两个或更多线程在执行过程中，<strong>由于争夺资源而造成的一种互相等待的状态</strong>。在这种状态下，没有任何线程能够继续前进，整个系统或部分系统因此陷入停滞。死锁是并发编程中常见的问题之一，尤其是在多线程环境下对共享资源进行访问时。</p>
</blockquote>
<h2><span id="死锁发生的必要条件">死锁发生的必要条件</span></h2><ol>
<li><strong>互斥条件：</strong>至少有一个资源必须处于非共享模式，即只能被一个线程占用。例如，文件写入权限通常就是互斥的。</li>
<li><strong>占有并等待条件：</strong>一个线程已经占有了至少一个资源，并且正在等待其他线程占有的资源。也就是说，该线程不会释放自己已获得的资源直到它获得了所有需要的资源。</li>
<li><strong>不可剥夺条件：</strong>资源不能被强制从某个线程中抢走，只能由拥有它的线程主动释放。这意味着一旦一个线程获得了某个资源，它可以在不自愿的情况下保持对该资源的控制权，直到它完成任务并释放资源。</li>
<li><strong>循环等待条件：</strong>存在一组等待资源的线程链，其中每个线程都在等待下一个线程当前占有的资源。例如，线程A等待线程B持有的资源，而线程B又在等待线程C持有的资源，以此类推，直到某一线程又在等待线程A持有的资源，形成一个闭环。</li>
</ol>
<p>一个线程同时获取多把锁就容易导致死锁</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Test6&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test6</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="type">Object</span> <span class="variable">lockA</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Object</span>();</span><br><span class="line">    <span class="keyword">static</span> <span class="type">Object</span> <span class="variable">lockB</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Object</span>();</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (lockA) &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;lockA &#123;&#125;&quot;</span>, Thread.currentThread().getName());</span><br><span class="line">                <span class="keyword">synchronized</span> (lockB) &#123;</span><br><span class="line">                    log.debug(<span class="string">&quot;lockB &#123;&#125;&quot;</span>, Thread.currentThread().getName());</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        sleep(<span class="number">1000</span>);</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t1&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (lockB) &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;lockB &#123;&#125;&quot;</span>, Thread.currentThread().getName());</span><br><span class="line">                <span class="keyword">synchronized</span> (lockA) &#123;</span><br><span class="line">                    log.debug(<span class="string">&quot;lockA &#123;&#125;&quot;</span>, Thread.currentThread().getName());</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        sleep(<span class="number">1000</span>);</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t2&quot;</span>);</span><br><span class="line"></span><br><span class="line">        t1.start();</span><br><span class="line">        t2.start();</span><br><span class="line">        log.debug(<span class="string">&quot;t1 &#123;&#125; t2 &#123;&#125;&quot;</span>, t1.getState(), t2.getState());</span><br><span class="line">        sleep(<span class="number">100</span>);</span><br><span class="line">        log.debug(<span class="string">&quot;t1 &#123;&#125; t2 &#123;&#125;&quot;</span>, t1.getState(), t2.getState());</span><br><span class="line">        sleep(<span class="number">2000</span>);</span><br><span class="line">        log.debug(<span class="string">&quot;t1 &#123;&#125; t2 &#123;&#125;&quot;</span>, t1.getState(), t2.getState());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<p><img src="/./../images/824b3abfa3a044f58184423af78b18c0.png" alt="img"><img src="" alt="点击并拖拽以移动"> </p>
<p>分析：</p>
<p>t1获得lockA的锁，t2获得lockB的锁，t1、t2都上锁成功，然后t1想要获得lockB，但是lockB被t2占有，t2只有等到全部执行完才能释放锁，但是t2中又要获得lockA的锁，但是lockA的锁被t1占有，又回到t1，t1也只能是执行完才能释放锁，然后t1和t2就互相等待对方放锁，造成死锁。 </p>
<p> —-&gt; 定位死锁的工具：jconsole</p>
<h2><span id="哲学家问题">哲学家问题</span></h2><ul>
<li>有五位哲学家，围坐在圆桌旁。 </li>
<li>他们只做两件事，思考和吃饭，思考一会吃口饭，吃完饭后接着思考。 </li>
<li>吃饭时要用两根筷子吃，桌上共有 5 根筷子，每位哲学家左右手边各有一根筷子。 </li>
<li>如果筷子被身边的人拿着，自己就得等待</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> cn.itcast.sychronized;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Test7&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test7</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">ChopSticks</span> <span class="variable">c1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ChopSticks</span>(<span class="string">&quot;1&quot;</span>);</span><br><span class="line">        <span class="type">ChopSticks</span> <span class="variable">c2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ChopSticks</span>(<span class="string">&quot;2&quot;</span>);</span><br><span class="line">        <span class="type">ChopSticks</span> <span class="variable">c3</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ChopSticks</span>(<span class="string">&quot;3&quot;</span>);</span><br><span class="line">        <span class="type">ChopSticks</span> <span class="variable">c4</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ChopSticks</span>(<span class="string">&quot;4&quot;</span>);</span><br><span class="line">        <span class="type">ChopSticks</span> <span class="variable">c5</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ChopSticks</span>(<span class="string">&quot;5&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">Philosopher</span> <span class="variable">p1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Philosopher</span>(<span class="string">&quot;p1&quot;</span>, c1, c2);</span><br><span class="line">        <span class="type">Philosopher</span> <span class="variable">p2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Philosopher</span>(<span class="string">&quot;p2&quot;</span>, c2, c3);</span><br><span class="line">        <span class="type">Philosopher</span> <span class="variable">p3</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Philosopher</span>(<span class="string">&quot;p3&quot;</span>, c3, c4);</span><br><span class="line">        <span class="type">Philosopher</span> <span class="variable">p4</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Philosopher</span>(<span class="string">&quot;p4&quot;</span>, c4, c5);</span><br><span class="line">        <span class="type">Philosopher</span> <span class="variable">p5</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Philosopher</span>(<span class="string">&quot;p5&quot;</span>, c5, c1);</span><br><span class="line"></span><br><span class="line">        p1.start();</span><br><span class="line">        p2.start();</span><br><span class="line">        p3.start();</span><br><span class="line">        p4.start();</span><br><span class="line">        p5.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ChopSticks</span> &#123;</span><br><span class="line">   String name;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">public</span> <span class="title function_">ChopSticks</span><span class="params">(String name)</span> &#123;</span><br><span class="line">       <span class="built_in">this</span>.name = name;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="meta">@Override</span></span><br><span class="line">   <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">       <span class="keyword">return</span> <span class="string">&quot;筷子 &#123; &quot;</span> + name + <span class="string">&quot;&#125;&quot;</span>;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Philosopher&quot;)</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Philosopher</span> <span class="keyword">extends</span> <span class="title class_">Thread</span>&#123;</span><br><span class="line">    <span class="keyword">final</span> ChopSticks left;</span><br><span class="line">    <span class="keyword">final</span> ChopSticks right;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Philosopher</span><span class="params">(String name, ChopSticks left, ChopSticks right)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(name); <span class="comment">// 线程名字</span></span><br><span class="line">        <span class="built_in">this</span>.left = left;</span><br><span class="line">        <span class="built_in">this</span>.right = right;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">eat</span><span class="params">()</span> &#123;</span><br><span class="line">        log.debug(<span class="string">&quot;&#123;&#125; eat&quot;</span>, Thread.currentThread().getName());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (left) &#123;</span><br><span class="line">                <span class="keyword">synchronized</span> (right) &#123;</span><br><span class="line">                    eat();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<p><img src="/./../images/a9288f2e51a34287858f1216a46b81b0.png" alt="img"><img src="" alt="点击并拖拽以移动"> </p>
<h1><span id="活锁">活锁</span></h1><blockquote>
<p>活锁（Livelock）是并发编程中的一种问题，类似于死锁，但它涉及的是线程虽然没有被阻塞，但却无法继续向前推进的情况。在活锁的情况下，线程不断地尝试执行某项操作但总是失败，并且不断地重复相同的操作，导致它们实际上没有取得任何进展。这种现象通常发生在试图避免死锁的过程中，特别是当多个线程相互改变状态以试图解决另一个线程的问题时。</p>
</blockquote>
<p>活锁出现在两个线程互相改变对方的结束条件，最后谁也无法结束。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Test8&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test8</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">volatile</span> <span class="type">int</span> <span class="variable">cnt</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">           <span class="keyword">while</span> (cnt &gt; <span class="number">0</span>) &#123;</span><br><span class="line">               cnt --;</span><br><span class="line">               <span class="keyword">try</span> &#123;</span><br><span class="line">                   sleep(<span class="number">100</span>);</span><br><span class="line">               &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                   e.printStackTrace();</span><br><span class="line">               &#125;</span><br><span class="line">               log.debug(<span class="string">&quot;t1 : &#123;&#125;&quot;</span>, cnt);</span><br><span class="line">           &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t1&quot;</span>).start();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">           <span class="keyword">while</span> (cnt &lt; <span class="number">100</span>) &#123;</span><br><span class="line">               cnt ++;</span><br><span class="line">               <span class="keyword">try</span> &#123;</span><br><span class="line">                   sleep(<span class="number">100</span>);</span><br><span class="line">               &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                   e.printStackTrace();</span><br><span class="line">               &#125;</span><br><span class="line">               log.debug(<span class="string">&quot;t2 : &#123;&#125;&quot;</span>, cnt);</span><br><span class="line">           &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t2&quot;</span>).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<p><img src="/./../images/137f3cd4c53443548aeadd96a02d8527.png" alt="img"><img src="" alt="点击并拖拽以移动"> </p>
<h1><span id="饥饿">饥饿</span></h1><h2><span id="概念">概念</span></h2><blockquote>
<p> “饥饿”（Starvation）是指一个线程由于无法获得所需的资源而无法继续执行的情况。尽管该线程没有被阻塞，但由于其他线程频繁地抢占资源，导致这个线程得不到足够的CPU时间或其他必要的资源来推进其任务</p>
</blockquote>
<h2><span id="饥饿的原因">饥饿的原因</span></h2><ol>
<li><strong>资源竞争：</strong>当多个线程竞争有限的资源时，如果没有公平的调度机制，某些线程可能会始终得不到资源，从而导致饥饿。例如，如果系统总是优先处理高优先级的任务，那么低优先级的任务可能永远得不到执行的机会。</li>
<li><strong>不恰当的锁机制：</strong>在使用锁进行同步控制时，如果某个线程长时间持有锁而不释放，其他等待该锁的线程就会被阻塞，可能导致这些线程出现饥饿现象。</li>
<li><strong>忙等待（Busy-waiting）：</strong>如果一个线程通过忙等待的方式来等待某个条件成立，而这个条件很少或几乎不会成立，那么这个线程就会一直消耗CPU资源，同时无法完成实际的工作。</li>
<li><strong>不公平的调度器：</strong>操作系统或运行时环境中的线程调度器如果没有实现公平调度算法，也可能导致某些线程长期得不到执行机会。</li>
</ol>
<h1><span id="reentrantlock"><strong>ReentrantLock</strong></span></h1><blockquote>
<p>ReentrantLock reentrantLock &#x3D; new ReentrantLock(true);</p>
<p>reentrantLock.lock();</p>
<p>try {</p>
<p>  &#x2F;&#x2F; 临界区代码</p>
<p>} finally {</p>
<p>  reentrantLock.unlock()</p>
<p>}</p>
</blockquote>
<blockquote>
<p>ReentrantLock(false) : 非公平锁</p>
<p>ReentrantLock(true) : 公平锁</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Test&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">ReentrantLock</span> <span class="variable">reentrantLock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>(<span class="literal">true</span>);</span><br><span class="line">    <span class="keyword">static</span> <span class="type">int</span> <span class="variable">cnt</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            reentrantLock.lock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">10000</span>; i++) &#123;</span><br><span class="line">                    cnt++;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                reentrantLock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t1&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            reentrantLock.lock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">10000</span>; i++) &#123;</span><br><span class="line">                    cnt--;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                reentrantLock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t2&quot;</span>);</span><br><span class="line"></span><br><span class="line">        t1.start();</span><br><span class="line">        t2.start();</span><br><span class="line">        t1.join();</span><br><span class="line">        t2.join();</span><br><span class="line">        log.debug(<span class="string">&quot;&#123;&#125;&quot;</span>,cnt);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<h2><span id="基本锁操作">基本锁操作</span></h2><blockquote>
<p><strong>lock()：</strong></p>
<ul>
<li>获取锁。</li>
<li>如果锁已经被其他线程持有，则当前线程将被阻塞，直到获取到锁为止。</li>
</ul>
<p><strong>lockInterruptibly() throws InterruptedException：</strong></p>
<ul>
<li>获取锁，但可以响应中断。</li>
<li>如果当前线程在等待获取锁的过程中被中断，则抛出 InterruptedException 异常并退出等待状态。</li>
</ul>
<p><strong>tryLock()：</strong></p>
<ul>
<li>尝试获取锁，如果锁未被其他线程持有，则立即返回 true；否则立即返回 false，不会阻塞当前线程。</li>
</ul>
<p><strong>tryLock(long timeout, TimeUnit unit) throws InterruptedException：</strong></p>
<ul>
<li>在给定的时间内尝试获取锁。</li>
<li>如果在指定时间内成功获取锁，则返回 true；如果超时或者当前线程被中断，则返回 false 或抛出 InterruptedException。</li>
</ul>
<p><strong>unlock()：</strong></p>
<ul>
<li>释放锁。</li>
<li>每次调用 lock() 方法获得一次锁后，必须对应地调用一次 unlock() 来释放锁。通常在 finally 块中调用以确保即使发生异常也能正确释放锁。</li>
</ul>
</blockquote>
<h2><span id="查看锁状态的方法">查看锁状态的方法</span></h2><blockquote>
<ul>
<li><strong>isHeldByCurrentThread()：</strong>判断当前线程是否持有该锁。</li>
<li><strong>getHoldCount()：</strong>返回当前线程获取这个锁的次数（重入计数）。每次调用 lock() 方法都会增加计数，每次调用 unlock() 方法都会减少计数。</li>
<li><strong>isLocked()：</strong>判断锁是否被任意一个线程持有。</li>
<li><strong>hasQueuedThreads()：</strong>查询是否有线程正在等待获取此锁。</li>
</ul>
</blockquote>
<h2><span id="条件变量相关的方法">条件变量相关的方法</span></h2><blockquote>
<p><strong>newCondition()：</strong></p>
<ul>
<li>创建一个新的 Condition 实例，与当前锁关联。</li>
<li>可以使用条件变量来实现类似于 Object.wait() 和 Object.notify() 的功能，但更加灵活和强大。</li>
</ul>
</blockquote>
<h2><span id="可重入锁">可重入锁</span></h2><p>这是指一个线程可以尝试多次获取同一个锁，并且不会发生死锁的情况。每次获取锁（调用lock()方法）都需要相应的释放锁（调用unlock()方法）。锁获取次数与锁释放次数需要匹配。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ReentrantLock 可重入锁</span></span><br><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Test2&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test2</span> &#123;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">static</span> <span class="type">ReentrantLock</span> <span class="variable">reentrantLock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>();</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">method1</span><span class="params">()</span> &#123;</span><br><span class="line">        reentrantLock.lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;method1 running&quot;</span>);</span><br><span class="line">            method2();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            reentrantLock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">method2</span><span class="params">()</span> &#123;</span><br><span class="line">        reentrantLock.lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;method2 running&quot;</span>);</span><br><span class="line">            method3();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            reentrantLock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">method3</span><span class="params">()</span> &#123;</span><br><span class="line">        reentrantLock.lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;method3 running&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            reentrantLock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        method1();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<p>执行结果：</p>
<p>10:17:12 [main] c.Test2 - method1 running<br> 10:17:12 [main] c.Test2 - method2 running<br> 10:17:12 [main] c.Test2 - method3 running </p>
<h2><span id="可打断lockinterruptibly">可打断(lockInterruptibly)</span></h2><p>这个方法允许你以一种可以响应中断的方式获取锁。如果当前线程在调用lockInterruptibly()方法时没有被打断，并且能够获取到锁，则它将继续执行；但如果此时有另一个线程已经持有了这个锁，那么当前线程将被阻塞，直到锁可用或当前线程被中断。<br> <strong>如果在等待获取锁的过程中收到了中断请求</strong>（即另一个线程调用了当前线程的interrupt()方法），则会<strong>抛出InterruptedException异常</strong>，从而允许你捕获这个异常并进行相应的处理。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 可打断</span></span><br><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Test3&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test3</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="type">ReentrantLock</span> <span class="variable">lock</span> <span class="operator">=</span>  <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>();</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;t1 running&quot;</span>);</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                lock.lockInterruptibly();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;t1:在等锁过程中被打断&quot;</span>);</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;t1 获取锁 &#123;&#125;&quot;</span>, System.currentTimeMillis());</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                lock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t1&quot;</span>);</span><br><span class="line">        lock.lock();</span><br><span class="line">        log.debug(<span class="string">&quot;主线程获得锁&quot;</span>);</span><br><span class="line">        t1.start();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            sleep(<span class="number">1000</span>);</span><br><span class="line">            t1.interrupt(); <span class="comment">// 打断t1</span></span><br><span class="line">            log.debug(<span class="string">&quot;执行打断&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;主线程释放锁&quot;</span>);</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<p><img src="/./../images/c2ead97c3aab40918cd54e89b8562830.png" alt="img"><img src="" alt="点击并拖拽以移动"> </p>
<h2><span id="不可打断">不可打断</span></h2><p>在ReentrantLock中，默认的锁获取方法lock()是不可中断的。这意味着如果一个线程尝试获取一个已经被其他线程持有的锁，它将会一直阻塞直到成功获取到锁，<strong>即使这个线程在这期间被中断（即调用了该线程的interrupt()方法），也不会抛出InterruptedException，而是继续等待直至获得锁</strong>。这种行为可以被视为“不可打断”。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 不可打断</span></span><br><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Test4&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test4</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="type">ReentrantLock</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>();</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;t1 启动 &#123;&#125;&quot;</span>, System.currentTimeMillis());</span><br><span class="line">            lock.lock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;t1 获得锁 &#123;&#125;&quot;</span>, System.currentTimeMillis());</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;t1 释放锁 &#123;&#125;&quot;</span>, System.currentTimeMillis());</span><br><span class="line">                lock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t1&quot;</span>);</span><br><span class="line"></span><br><span class="line">        lock.lock();</span><br><span class="line">        log.debug(<span class="string">&quot;主线程获得锁 &#123;&#125;&quot;</span>, System.currentTimeMillis());</span><br><span class="line">        t1.start();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;执行打断 &#123;&#125;&quot;</span>, System.currentTimeMillis());</span><br><span class="line">            sleep(<span class="number">1000</span>);</span><br><span class="line">            t1.interrupt();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;主线程释放锁 &#123;&#125;&quot;</span>, System.currentTimeMillis());</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<p>执行结果：</p>
<blockquote>
<p>10:18:41 [main] c.Test4 - 主线程获得锁 1742696321911<br> 10:18:41 [main] c.Test4 - 执行打断 1742696321917<br> 10:18:41 [t1] c.Test4 - t1 启动 1742696321917<br> 10:18:42 [main] c.Test4 - 主线程释放锁 1742696322931<br> 10:18:42 [t1] c.Test4 - t1 获得锁 1742696322931<br> 10:18:42 [t1] c.Test4 - t1 释放锁 1742696322931</p>
</blockquote>
<h2><span id="锁超时trylock">锁超时(tryLock)</span></h2><blockquote>
<ul>
<li><strong>tryLock()：</strong>尝试立即获取锁。如果锁当前没有被其他线程持有，则该方法会成功获取锁并返回true；如果锁已经被其他线程持有，则该方法不会阻塞，而是立刻返回false。</li>
<li><strong>tryLock(long timeout, TimeUnit unit)：</strong>尝试在指定的时间内获取锁。如果在这个时间段内成功获取到了锁，则返回true；如果在这个时间段内未能获取到锁（即锁一直被其他线程持有），则返回false。此外，如果在等待期间当前线程被中断，它将抛出InterruptedException。</li>
</ul>
</blockquote>
<h3><span id="立刻返回">立刻返回</span></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 锁超时 --- 立刻返回</span></span><br><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Test5&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test5</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="type">ReentrantLock</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>();</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;t1 running&quot;</span>);</span><br><span class="line">            <span class="keyword">if</span> (!lock.tryLock()) &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;t1 获取锁失败, 立刻返回&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;t1 获得锁成功&quot;</span>);</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                lock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t1&quot;</span>);</span><br><span class="line"></span><br><span class="line">        lock.lock();</span><br><span class="line">        t1.start();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            sleep(<span class="number">1000</span>);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<h3><span id><img src="/./../images/1235f9da30244a859ad5c81b19c4eb8c.png" alt="img"><img src="" alt="点击并拖拽以移动"></span></h3><h3><span id="超时释放">超时释放</span></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Test5&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test6</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="type">ReentrantLock</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>();</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;t1 running&quot;</span>);</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">// 超时释放</span></span><br><span class="line">                <span class="keyword">if</span> (!lock.tryLock(<span class="number">1</span>, TimeUnit.SECONDS)) &#123;</span><br><span class="line">                    log.debug(<span class="string">&quot;t1 1s尝试获得锁失败&quot;</span>);</span><br><span class="line">                    <span class="keyword">return</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;t1 获得锁成功&quot;</span>);</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                lock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t1&quot;</span>);</span><br><span class="line"></span><br><span class="line">        lock.lock();</span><br><span class="line">        t1.start();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            sleep(<span class="number">1500</span>);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;主线程释放锁&quot;</span>);</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<p><img src="/./../images/1782ad0c5b2d4513a0916fd75b9fc1dc.png" alt="img"><img src="" alt="点击并拖拽以移动">  <strong>例子：哲学家问题</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Test7&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test7</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">ChopSticks</span> <span class="variable">c1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ChopSticks</span>(<span class="string">&quot;1&quot;</span>);</span><br><span class="line">        <span class="type">ChopSticks</span> <span class="variable">c2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ChopSticks</span>(<span class="string">&quot;2&quot;</span>);</span><br><span class="line">        <span class="type">ChopSticks</span> <span class="variable">c3</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ChopSticks</span>(<span class="string">&quot;3&quot;</span>);</span><br><span class="line">        <span class="type">ChopSticks</span> <span class="variable">c4</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ChopSticks</span>(<span class="string">&quot;4&quot;</span>);</span><br><span class="line">        <span class="type">ChopSticks</span> <span class="variable">c5</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ChopSticks</span>(<span class="string">&quot;5&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">Philosopher</span> <span class="variable">p1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Philosopher</span>(<span class="string">&quot;p1&quot;</span>, c1, c2);</span><br><span class="line">        <span class="type">Philosopher</span> <span class="variable">p2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Philosopher</span>(<span class="string">&quot;p2&quot;</span>, c2, c3);</span><br><span class="line">        <span class="type">Philosopher</span> <span class="variable">p3</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Philosopher</span>(<span class="string">&quot;p3&quot;</span>, c3, c4);</span><br><span class="line">        <span class="type">Philosopher</span> <span class="variable">p4</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Philosopher</span>(<span class="string">&quot;p4&quot;</span>, c4, c5);</span><br><span class="line">        <span class="type">Philosopher</span> <span class="variable">p5</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Philosopher</span>(<span class="string">&quot;p5&quot;</span>, c5, c1);</span><br><span class="line"></span><br><span class="line">        p1.start();</span><br><span class="line">        p2.start();</span><br><span class="line">        p3.start();</span><br><span class="line">        p4.start();</span><br><span class="line">        p5.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ChopSticks</span> <span class="keyword">extends</span> <span class="title class_">ReentrantLock</span> &#123;</span><br><span class="line">    String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">ChopSticks</span><span class="params">(String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">toString</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;筷子&#123;&quot;</span> + name + <span class="string">&#x27;&#125;&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Philosopher&quot;)</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Philosopher</span> <span class="keyword">extends</span> <span class="title class_">Thread</span> &#123;</span><br><span class="line">    ChopSticks left;</span><br><span class="line">    ChopSticks right;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Philosopher</span><span class="params">(String name, ChopSticks left, ChopSticks right)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(name);</span><br><span class="line">        <span class="built_in">this</span>.left = left;</span><br><span class="line">        <span class="built_in">this</span>.right = right;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">eat</span><span class="params">()</span>&#123;</span><br><span class="line">        log.debug(<span class="string">&quot;&#123;&#125; eating&quot;</span>, Thread.currentThread().getName());</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            sleep(<span class="number">1000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">            <span class="comment">// 尝试获得左边的筷子</span></span><br><span class="line">            <span class="keyword">if</span> (left.tryLock()) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    <span class="comment">// 尝试获得右边的筷子</span></span><br><span class="line">                    <span class="keyword">if</span> (right.tryLock()) &#123;</span><br><span class="line">                        <span class="keyword">try</span> &#123;</span><br><span class="line">                            eat();</span><br><span class="line">                        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                            right.unlock();</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                    left.unlock();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<h2><span id="公平锁x2f非公平锁">公平锁&#x2F;非公平锁</span></h2><h3><span id="非公平锁">非公平锁</span></h3><ul>
<li><strong>定义：</strong>在非公平锁机制下，锁不会保证按照请求的先后顺序来分配。当锁可用时，任何一个尝试获取锁的线程都有机会获得锁，包括那些刚刚释放了这个锁并且立刻再次尝试获取它的线程。</li>
<li><strong>默认行为：</strong>如果不特别指定，ReentrantLock默认采用的是非公平锁策略（即new ReentrantLock()等同于new ReentrantLock(false)）。</li>
<li><strong>性能：</strong>通常情况下，非公平锁可以获得更高的吞吐量，因为它减少了线程上下文切换的次数，并且允许线程在锁刚被释放时迅速重新获取锁，而不需要排队等待。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 非公平锁</span></span><br><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Test8&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test8</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="type">ReentrantLock</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>(<span class="literal">false</span>);</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">500</span>; i ++) &#123;</span><br><span class="line">            <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">                lock.lock();</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    log.debug(<span class="string">&quot;&#123;&#125; 获得锁成功&quot;</span>, Thread.currentThread().getName());</span><br><span class="line">                &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                    lock.unlock();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;, <span class="string">&quot;t&quot;</span> + i).start();</span><br><span class="line">        &#125;</span><br><span class="line">        Thread.sleep(<span class="number">1</span>);</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            log.debug(<span class="string">&quot;start-----------------------&quot;</span>);</span><br><span class="line">            lock.lock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;&#123;&#125; 获得锁成功 running&quot;</span>, Thread.currentThread().getName());</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                lock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;强行抢夺&quot;</span>).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<p> <img src="/./../images/a095c152aa774e01b24e9b73518d44de.png" alt="img"><img src="" alt="点击并拖拽以移动"> </p>
<h3><span id="公平锁">公平锁</span></h3><ul>
<li><strong>定义：</strong>当使用公平锁时，锁会按照线程请求的顺序来分配。也就是说，最早提出请求的线程将最先被授予锁。这有助于避免“饥饿”现象，即某些线程永远无法获得锁。</li>
<li><strong>实现：</strong>要创建一个公平锁的ReentrantLock实例，可以在构造函数中传入参数true，例如new ReentrantLock(true)。</li>
<li><strong>性能：</strong>由于需要维护线程请求锁的顺序，公平锁可能会导致较低的吞吐量。因为每当有线程释放锁后，系统必须检查等待队列中的下一个线程是否可以获取锁，而不是简单地允许当前正在尝试获取锁的线程直接获取它。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 公平锁</span></span><br><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Test8&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test8</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="type">ReentrantLock</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>(<span class="literal">true</span>);</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">500</span>; i ++) &#123;</span><br><span class="line">            <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">                lock.lock();</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    log.debug(<span class="string">&quot;&#123;&#125; 获得锁成功&quot;</span>, Thread.currentThread().getName());</span><br><span class="line">                &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                    lock.unlock();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;, <span class="string">&quot;t&quot;</span> + i).start();</span><br><span class="line">        &#125;</span><br><span class="line">        Thread.sleep(<span class="number">1</span>);</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            log.debug(<span class="string">&quot;start-----------------------&quot;</span>);</span><br><span class="line">            lock.lock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;&#123;&#125; 获得锁成功 running&quot;</span>, Thread.currentThread().getName());</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                lock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;强行抢夺&quot;</span>).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<h3><span id><img src="/./../images/17bd9de5d9e94b609650f44fbf2baa93.png" alt="img"><img src="" alt="点击并拖拽以移动"></span></h3><h2><span id="awaitx2fcondition">await&#x2F;Condition</span></h2><h3><span id="等待条件await方法系列"><strong>等待条件（await方法系列）：</strong></span></h3><p>当一个线程需要等待某个特定条件发生时，可以调用Condition对象的await()方法进入等待状态。这会导致当前线程释放锁并等待，直到另一个线程调用了同一个Condition对象的signal()或signalAll()方法。常见的await方法包括：</p>
<ul>
<li>await()：使当前线程进入等待状态，直到被通知或中断。</li>
<li>awaitUninterruptibly()：类似于await()，但是不会响应中断。</li>
<li>awaitNanos(long nanosTimeout)：尝试等待指定的时间长度，如果超时则返回剩余时间。</li>
<li>awaitUntil(Date deadline)：等待直到指定的时间点，如果到达截止时间还未被通知，则继续执行。</li>
</ul>
<h3><span id="通知条件signal方法系列">通知条件（signal方法系列）：</span></h3><p>当一个线程修改了共享资源并且认为可能满足了一个或多个正在等待的线程的条件时，它可以调用Condition对象的signal()或signalAll()方法来唤醒等待的线程。</p>
<ul>
<li>signal()：唤醒一个等待此Condition的线程。如果有多个线程在等待，则选择其中的一个进行唤醒。</li>
<li>signalAll()：唤醒所有等待此Condition的线程。</li>
</ul>
<blockquote>
<p>可以把Condition实例看作对应的等待队列，不同的线程可以调用不同的等待队列的await方法，使得当前线程进入当前的等待队列中 </p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 等待队列 Condition实例</span></span><br><span class="line"><span class="comment">// 唤醒线程：signal或signalAll</span></span><br><span class="line"><span class="meta">@Slf4j(topic = &quot;c.Test9&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test9</span> &#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="type">ReentrantLock</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>();</span><br><span class="line">    <span class="keyword">static</span> <span class="type">Condition</span> <span class="variable">waitBreadQueue</span> <span class="operator">=</span> lock.newCondition();</span><br><span class="line">    <span class="keyword">static</span> <span class="type">Condition</span> <span class="variable">waitCoffeeQueue</span> <span class="operator">=</span> lock.newCondition();</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">volatile</span> <span class="type">boolean</span> <span class="variable">hasBread</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">volatile</span> <span class="type">boolean</span> <span class="variable">hasCoffee</span> <span class="operator">=</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                lock.lock();</span><br><span class="line">                <span class="keyword">while</span> (!hasCoffee) &#123;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        log.debug(<span class="string">&quot;等待咖啡&quot;</span>);</span><br><span class="line">                        waitCoffeeQueue.await(); <span class="comment">// 等咖啡队列</span></span><br><span class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                log.debug(<span class="string">&quot;t1 收到咖啡&quot;</span>);</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;t1 释放锁&quot;</span>);</span><br><span class="line">                lock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t1&quot;</span>).start();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                lock.lock();</span><br><span class="line">                <span class="keyword">while</span> (!hasBread) &#123;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        log.debug(<span class="string">&quot;等待面包&quot;</span>);</span><br><span class="line">                        waitBreadQueue.await(); <span class="comment">// 等面包队列</span></span><br><span class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                log.debug(<span class="string">&quot;t2 收到面包&quot;</span>);</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                log.debug(<span class="string">&quot;t2 释放锁&quot;</span>);</span><br><span class="line">                lock.unlock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, <span class="string">&quot;t2&quot;</span>).start();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        sleep(<span class="number">1000</span>);</span><br><span class="line">        handleCoffee();</span><br><span class="line">        sleep(<span class="number">1000</span>);</span><br><span class="line">        handleBread();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">handleCoffee</span><span class="params">()</span> &#123;</span><br><span class="line">        lock.lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;发咖啡&quot;</span>);</span><br><span class="line">            hasCoffee = <span class="literal">true</span>;</span><br><span class="line">            waitCoffeeQueue.signal(); <span class="comment">// 唤醒等待咖啡的线程</span></span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">handleBread</span><span class="params">()</span> &#123;</span><br><span class="line">        lock.lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            log.debug(<span class="string">&quot;发面包&quot;</span>);</span><br><span class="line">            hasBread = <span class="literal">true</span>;</span><br><span class="line">            waitBreadQueue.signal(); <span class="comment">// 唤醒等待面包的线程</span></span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><img src="" alt="点击并拖拽以移动"></p>
<p><img src="/./../images/ff3e63ff47fa40bdb03fc4c7c12fa562.png" alt="img"><img src="" alt="点击并拖拽以移动"> </p>
<hr>
<p><strong>如有错误，欢迎指正！！！</strong> </p>
<p><strong>图源来自网络，侵删！</strong></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="http://xuanskeys.github.io">xuanskeys</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="http://xuanskeys.github.io/2025/04/20/JUC2/">http://xuanskeys.github.io/2025/04/20/JUC2/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="http://xuanskeys.github.io" target="_blank">XuanCode</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/1/">1</a></div><div class="post-share"><div class="social-share" data-image="/image/person.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><a class="pagination-related" href="/2025/04/20/JUC1/" title="JUC并发编程1(初识进程和线程)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info"><div class="info-1"><div class="info-item-1">上一篇</div><div class="info-item-2">JUC并发编程1(初识进程和线程)</div></div><div class="info-2"><div class="info-item-1"> 初识进程和线程初识进程：定义：  进程（Process）是计算机中的程序关于某数据集合上的一次运行活动，是系统进行资源分配的基本单位，是操作系统结构的基础。在早期面向进程设计的计算机结构中，进程是程序的基本执行实体；在当代面向线程设计的计算机结构中，进程是线程的容器。程序是指令、数据及其组织形式的描述，进程是程序的实体。（百度百科） 进程由程序、数据和进程控制块三部分组成。   什么是进程？ 狭义定义：进程是正在运行的程序的实例。 广义定义：进程是一个具有一定独立功能的程序关于某个数据集合的一次运行活动。它是操作系统动态执行的基本单元，在传统的操作系统中，进程既是基本的分配单元，也是基本的执行单元。   eg：进程可以看做是程序的实例，你可以打开多个程序，每一个程序就是一个进程（比如你重复打开QQ登录不同的用户，每一个用户登录的那个程序就是一个进程）。   如果你关闭一个窗口，那么这个进程也就结束了  概念：1.进程是一个实体。 ...</div></div></div></a><a class="pagination-related" href="/2025/04/20/JUC3/" title="Java并发编程3(CAS)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-right"><div class="info-1"><div class="info-item-1">下一篇</div><div class="info-item-2">Java并发编程3(CAS)</div></div><div class="info-2"><div class="info-item-1">Java内存模型(JMM)概念百度百科：java内存模型_百度百科  Java内存模型（Java Memory Model,...</div></div></div></a></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/2025/04/20/JUC1/" title="JUC并发编程1(初识进程和线程)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-04-20</div><div class="info-item-2">JUC并发编程1(初识进程和线程)</div></div><div class="info-2"><div class="info-item-1"> 初识进程和线程初识进程：定义：  进程（Process）是计算机中的程序关于某数据集合上的一次运行活动，是系统进行资源分配的基本单位，是操作系统结构的基础。在早期面向进程设计的计算机结构中，进程是程序的基本执行实体；在当代面向线程设计的计算机结构中，进程是线程的容器。程序是指令、数据及其组织形式的描述，进程是程序的实体。（百度百科） 进程由程序、数据和进程控制块三部分组成。   什么是进程？ 狭义定义：进程是正在运行的程序的实例。 广义定义：进程是一个具有一定独立功能的程序关于某个数据集合的一次运行活动。它是操作系统动态执行的基本单元，在传统的操作系统中，进程既是基本的分配单元，也是基本的执行单元。   eg：进程可以看做是程序的实例，你可以打开多个程序，每一个程序就是一个进程（比如你重复打开QQ登录不同的用户，每一个用户登录的那个程序就是一个进程）。   如果你关闭一个窗口，那么这个进程也就结束了  概念：1.进程是一个实体。 ...</div></div></div></a><a class="pagination-related" href="/2025/04/20/JUC4/" title="Java并发编程4（JUC篇）"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-04-20</div><div class="info-item-2">Java并发编程4（JUC篇）</div></div><div class="info-2"><div class="info-item-1">本篇文章重点介绍JUC（java.util.concurrent）  JUC是”java.util.concurrent”包的简称，它是Java提供的一个并发工具包，旨在简化多线程编程，提供了丰富的类和接口来帮助开发者更高效、更安全地编写并发程序。JUC包增强了Java对并发的支持，解决了传统多线程编程中的一些难题，如死锁、竞争条件和资源管理等。    原子变量  基本类型原子变量 AtomicInteger  提供对整型值的原子操作，如加法、减法等。 方法示例：incrementAndGet(), decrementAndGet(), addAndGet(int delta), compareAndSet(int expect, int update)。  AtomicLong  类似于AtomicInteger，但是针对长整型（long）值。 方法与AtomicInteger相似，适用于需要处理较大数值的情况。  AtomicBoolean  支持布尔类型的原子操作。 方法示例：get(), set(boolean newValue),...</div></div></div></a><a class="pagination-related" href="/2025/04/20/JUC3/" title="Java并发编程3(CAS)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-04-20</div><div class="info-item-2">Java并发编程3(CAS)</div></div><div class="info-2"><div class="info-item-1">Java内存模型(JMM)概念百度百科：java内存模型_百度百科  Java内存模型（Java Memory Model,...</div></div></div></a><a class="pagination-related" href="/2025/04/20/Java%E8%99%9A%E6%8B%9F%E6%9C%BA/" title="Java虚拟机"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-04-20</div><div class="info-item-2">Java虚拟机</div></div><div class="info-2"><div class="info-item-1">JVM的概念百度百科：java虚拟机 什么是虚拟机？虚拟机是一种抽象化的计算机，通过在实际的计算机上仿真模拟各种计算机功能来实现的。 为什么要有JVM？  Java设计的初衷是使要建的能在任何平台上运行的程序不需要再在每个单独的平台上由程序员进行重写或重编译。 Java虚拟机使这个愿望变为可能，因为它能知道每条指令的长度和平台的其他特性。 JVM的设计目标是提供一个基于抽象规格描述的计算机模型，为解释程序开发人员提供的任何系统上运行。   什么是java虚拟机?JVM全称Java Virtual...</div></div></div></a><a class="pagination-related" href="/2025/04/20/Java%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%BC%96%E7%A8%8B/" title="Java面向对象编程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-04-20</div><div class="info-item-2">Java面向对象编程</div></div><div class="info-2"><div class="info-item-1">什么是面向对象编程(OOP)? 它将数据和相关操作封装在对象中，通过对象之间的交互来解决问题。 简单来说，就是世界上所有的物品，都可以是一个对象，对象是一种特殊的数据结构，里面存储物品的相关属性信息，类似于一张表结构。 类就相当于对象的一个模版，结构相同的对象可以使用同一个类来构造   JVM虚拟机JVM是什么? JVM（Java虚拟机）并不是直接安装在操作系统上的一个单独的实体或文件夹，而是一种抽象的计算模型，它通常是由一个程序或者软件包的一部分来实现的。当你在计算机上安装Java运行环境（例如，Java Development Kit, JDK 或者 Java Runtime Environment, JRE）时，实际上就包含了JVM的实现 当你运行一个Java程序时，比如通过命令行输入java...</div></div></div></a><a class="pagination-related" href="/2025/04/20/Oracle/" title="Oracle基本语法"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-04-20</div><div class="info-item-2">Oracle基本语法</div></div><div class="info-2"><div class="info-item-1">前言： 1.使用的数据库不同，所使用的语法也略有不同 2.SQL对大小写不敏感 3.Oracle中对引号里面的内容大小写敏感 3.表空间名、文件路径……等需要用单引号将其包含 4.一般引号里面的内容需要大写   准备工作：安装tips：PLSQL、Oracle以及客户端远程连接服务器笔记（仅供参考）-CSDN博客  （1）.Win+R打开services.msc     （2）启动一些服务： （qwq我不知道哪些有用，哪些没用，所以我都把打开了，不知道有没有负面影响，大家参考一下别的博客吧）     登录：1.打开SQL Plus命令行工具第一种方式：  第二种方式： （1）win+R 打开cmd   （2）输入sqlplus    2.以不同用户登录 注意： 1.使用用户口令这种形式登录的时候，是不显示密码的，口令输入的时候是不显示的，直接输就好 2.若是想以显示密码的形式输入，直接在用户名那一块输入：用户名&#x2F;密码 3.超级管理员（sys）输入时需要注意指定 as sysdba  SYSTEM（普通管理员）：...</div></div></div></a></div></div><hr class="custom-hr"/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="gitalk-container"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/image/person.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">xuanskeys</div><div class="author-info-description"></div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">10</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xuanskeys"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">欢迎来到XuanCode。更多详细信息请前往CSDN：https://blog.csdn.net/m0_73569492?type=blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">1.</span> <span class="toc-text">认识Java对象头</span></a></li><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">2.</span> <span class="toc-text">sychronized锁原理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">2.1.</span> <span class="toc-text">基本概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">2.2.</span> <span class="toc-text">工作原理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">2.2.1.</span> <span class="toc-text">1.作用在方法上</span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">2.2.2.</span> <span class="toc-text">2.作用在代码块上</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">2.3.</span> <span class="toc-text">工作机制</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">2.4.</span> <span class="toc-text">JVM优化锁</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">2.5.</span> <span class="toc-text">Monitor锁</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">2.6.</span> <span class="toc-text">wait&#x2F;notify</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">2.7.</span> <span class="toc-text">park&#x2F;unpark</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">3.</span> <span class="toc-text">线程状态转换案例</span></a></li><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">4.</span> <span class="toc-text">死锁</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">4.1.</span> <span class="toc-text">概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">4.2.</span> <span class="toc-text">死锁发生的必要条件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">4.3.</span> <span class="toc-text">哲学家问题</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">5.</span> <span class="toc-text">活锁</span></a></li><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">6.</span> <span class="toc-text">饥饿</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">6.1.</span> <span class="toc-text">概念</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">6.2.</span> <span class="toc-text">饥饿的原因</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">7.</span> <span class="toc-text">ReentrantLock</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">7.1.</span> <span class="toc-text">基本锁操作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">7.2.</span> <span class="toc-text">查看锁状态的方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">7.3.</span> <span class="toc-text">条件变量相关的方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">7.4.</span> <span class="toc-text">可重入锁</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">7.5.</span> <span class="toc-text">可打断(lockInterruptibly)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">7.6.</span> <span class="toc-text">不可打断</span></a></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">7.7.</span> <span class="toc-text">锁超时(tryLock)</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">7.7.1.</span> <span class="toc-text">立刻返回</span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">7.7.2.</span> <span class="toc-text"></span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">7.7.3.</span> <span class="toc-text">超时释放</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">7.8.</span> <span class="toc-text">公平锁&#x2F;非公平锁</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">7.8.1.</span> <span class="toc-text">非公平锁</span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">7.8.2.</span> <span class="toc-text">公平锁</span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">7.8.3.</span> <span class="toc-text"></span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link"><span class="toc-number">7.9.</span> <span class="toc-text">await&#x2F;Condition</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">7.9.1.</span> <span class="toc-text">等待条件（await方法系列）：</span></a></li><li class="toc-item toc-level-3"><a class="toc-link"><span class="toc-number">7.9.2.</span> <span class="toc-text">通知条件（signal方法系列）：</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2025/04/20/%E6%9C%80%E7%9F%AD%E8%B7%AF%E9%97%AE%E9%A2%98/" title="最短路问题">最短路问题</a><time datetime="2025-04-20T02:09:44.000Z" title="发表于 2025-04-20 10:09:44">2025-04-20</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2025/04/20/Java%E8%99%9A%E6%8B%9F%E6%9C%BA/" title="Java虚拟机">Java虚拟机</a><time datetime="2025-04-20T02:07:29.000Z" title="发表于 2025-04-20 10:07:29">2025-04-20</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2025/04/20/%E5%9F%BA%E7%A1%80%E7%AE%97%E6%B3%95/" title="基础算法">基础算法</a><time datetime="2025-04-20T02:03:22.000Z" title="发表于 2025-04-20 10:03:22">2025-04-20</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2025/04/20/JUC4/" title="Java并发编程4（JUC篇）">Java并发编程4（JUC篇）</a><time datetime="2025-04-20T02:01:01.000Z" title="发表于 2025-04-20 10:01:01">2025-04-20</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2025/04/20/JUC3/" title="Java并发编程3(CAS)">Java并发编程3(CAS)</a><time datetime="2025-04-20T01:59:28.000Z" title="发表于 2025-04-20 09:59:28">2025-04-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2025 By xuanskeys</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo 7.3.0</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly 5.3.5</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="前往评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"><script>(() => {
  const isShuoshuo = GLOBAL_CONFIG_SITE.pageType === 'shuoshuo'
  const option = null

  const commentCount = n => {
    const isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
    if (isCommentCount) {
      isCommentCount.textContent= n
    }
  }

  const initGitalk = (el, path) => {
    if (isShuoshuo) {
      window.shuoshuoComment.destroyGitalk = () => {
        if (el.children.length) {
          el.innerHTML = ''
          el.classList.add('no-comment')
        }
      }
    }

    const gitalk = new Gitalk({
      clientID: '',
      clientSecret: '',
      repo: 'xuanskeys.github.io',
      owner: 'xuanskeys',
      admin: ['xuanskeys'],
      updateCountCallback: commentCount,
      ...option,
      id: isShuoshuo ? path : (option && option.id) || '9144208cf60ba589ac48f9cb06cd3095'
    })

    gitalk.render('gitalk-container')
  }

  const loadGitalk = async(el, path) => {
    if (typeof Gitalk === 'function') initGitalk(el, path)
    else {
      await btf.getCSS('https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.css')
      await btf.getScript('https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.js')
      initGitalk(el, path)
    }
  }

  if (isShuoshuo) {
    'Gitalk' === 'Gitalk'
      ? window.shuoshuoComment = { loadComment: loadGitalk }
      : window.loadOtherComment = loadGitalk
    return
  }

  if ('Gitalk' === 'Gitalk' || !false) {
    if (false) btf.loadComment(document.getElementById('gitalk-container'), loadGitalk)
    else loadGitalk()
  } else {
    window.loadOtherComment = loadGitalk
  }
})()</script></div><script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/gh/xiabo2/CDN@latest/fishes.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="text-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div></body></html>